package cn.ichiva.tushare.sdk.common;

import cn.ichiva.tushare.sdk.tushare.entity.TuTable;

import java.io.*;

public class TuUtils {

    /**
     * 转CSV
     * @param tuShareTable
     * @param out
     */
    public static void writeCSV(TuTable tuShareTable, OutputStream out) throws IOException {
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out))){
            String[] fields = tuShareTable.getFields();
            for (int i = 0; i < fields.length - 1; i++) {
                writer.write(fields[i]);
                writer.write(',');
            }

            writer.write(fields[fields.length -1]);
            writer.write(SystemHelper.getLineEnd());

            for (String[] item : tuShareTable.getItems()) {
                for (int i = 0; i < item.length - 1; i++) {
                    writer.write(item[i] == null ? "'null'" : item[i]);
                    writer.write(',');
                }

                writer.write(item[item.length -1] == null ? "'null'" : item[item.length -1]);
                writer.write(SystemHelper.getLineEnd());
            }

            writer.flush();
        }
    }
}
